import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { TaskJobEntity } from '../../task/entity/job';
import { TaskRecordEntity } from '../../task/entity/record';
import { TaskTopicEntity } from '../../task/entity/topic';
import { TaskAppEntity } from '../../task/entity/app';
import { Utils } from '../../../comm/utils';

/**
 * 首页统计
 */
@Provide()
export class CountHomeService extends BaseService {
  @InjectEntityModel(TaskJobEntity)
  taskJobEntity: Repository<TaskJobEntity>;

  @InjectEntityModel(TaskTopicEntity)
  taskTopicEntity: Repository<TaskTopicEntity>;

  @InjectEntityModel(TaskAppEntity)
  taskAppEntity: Repository<TaskAppEntity>;

  @InjectEntityModel(TaskRecordEntity)
  taskRecordEntity: Repository<TaskRecordEntity>;

  @Inject()
  utils: Utils;

  /**
   * 顶部统计
   */
  async top() {
    // 应用数量
    const appCount = await this.taskAppEntity.count();
    // Topic数量
    const topicCount = await this.taskTopicEntity.count();
    // 任务数量
    const jobCount = await this.taskJobEntity.count();
    // 任务记录
    const recordCount = await this.taskRecordEntity.count();
    return {
      appCount,
      topicCount,
      jobCount,
      recordCount,
    };
  }

  /**
   * 记录图表
   * @param dayCount
   * @returns
   */
  async chart(dayCount = 15) {
    const result = {
      datas: [],
      dates: [],
    };
    const dates = await this.utils.getRecentlyDates(dayCount);
    const count = await this.nativeQuery(
      `SELECT
            count( a.id ) AS count,
            LEFT ( a.createTime, 10 ) AS time
        FROM
            task_record a
        WHERE
            DATE_SUB( CURDATE( ), INTERVAL ? DAY ) <= a.createTime
        GROUP BY
            LEFT ( a.createTime, 10 )`,
      [dayCount]
    );

    dates.forEach(date => {
      let data = 0;
      for (const item of count) {
        if (date === item.time) {
          data = item.count;
          break;
        }
      }
      result.dates.push(date.substring(5, 10));
      result.datas.push(data);
    });
    return result;
  }
}
